import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

const dependencies = require('./package.json').dependencies

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      symbolId: 'icon-[dir]-[name]',
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/base.scss";`
      }
    }
  },
  build: {
    outDir: 'dist',
    assetsDir: 'static',
    brotliSize: false, // 设置为false将禁用构建的brotli压缩大小报告。可以稍微提高构建速度
    minify: true, // 开启压缩
    rollupOptions: {
        treeshake: true, // 开启 Tree Shaking，消除未使用的代码，减小最终的包大小
        output: {
            // 根据不同的js库 拆分包，减少index.js包体积
            manualChunks(id) {
                if (id.includes('node_modules')) {
                    // 指定需要拆分的第三方库或模块
                    console.info('id', id)
                    const dependenciesKeys = Object.keys(dependencies);
                    const match = dependenciesKeys.find((item) => {
                        return id.includes(item);
                    });
                    console.info('match', match)
                    const notSplit = ['vue', 'element-plus'];
                    if (match && !notSplit.includes(match)) {
                        return match;
                    }
                }
            },
        },
        commonjsOptions: {
            requireReturnsDefault: 'namespace', // 要求ES模块返回其名称空间
        }
    },
  },
})
